<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="入库时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="购买时间" prop="applyTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admAssetStore:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:admAssetStore:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admAssetStore:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown @command="handleMoreCommand"
              v-hasPermi="['system:admBookStore:import', 'system:admBookStore:export', 'system:admBookStore:downloadTemplate']">
              <el-button type="warning" plain size="default">
                导入导出
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="download-template">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">下载模板</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="import-data">
                    <el-icon style="vertical-align: middle">
                      <Upload />
                    </el-icon>
                    <span style="margin-left: 4px">导入数据</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="export-data">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">导出数据</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admAssetStoreList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="入库人" align="center" prop="storeId" >
          <template #default="scope">
            {{ scope.row.storeName }}
          </template>
        </el-table-column>
        <el-table-column label="入库部门" align="center" prop="deptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="storeTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.storeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="资产名称" align="center" prop="assetName" />
        <el-table-column label="使用人" align="center" prop="useId" width="120">
          <template #default="scope">
            <el-tooltip :content="scope.row.useName" placement="top" :disabled="!scope.row.useName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.useName || "未设置" }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="共同使用人" align="center" prop="jointUserId" width="110" >
          <template #default="scope">
            <el-tooltip :content="scope.row.jointUserName" placement="top" :disabled="!scope.row.jointUserName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.jointUserName || "未设置" }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用部门" align="center" prop="useDeptId"  >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.useDeptName || "未设置" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编号" align="center" prop="number" >
          <template #default="scope">
            <el-tooltip :content="scope.row.number" placement="top" :disabled="!scope.row.number">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.number }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="购买时间" align="center" prop="purchaseTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.purchaseTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="品牌" align="center" prop="brand" >
          <template #default="scope">
            <el-tooltip :content="scope.row.brand" placement="top" :disabled="!scope.row.brand">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.brand }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="序列号" align="center" prop="serialNumber" >
          <template #default="scope">
            <el-tooltip :content="scope.row.serialNumber" placement="top" :disabled="!scope.row.serialNumber">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.serialNumber }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="借出状态" align="center" prop="isLend">
          <template #default="scope">
            <dict-tag :options="asset_lend_status" :value="scope.row.isLend" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:admAssetStore:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:admAssetStore:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改资产入库登记对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible"
      ref="dialogRef" 
      width="900px" 
      append-to-body
      class="seal-dialog"
      @opened="handleDialogOpen"
    >
      <template #default>
        <el-form ref="admAssetStoreFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="入库人" prop="storeId">    
                <el-input v-model="form.storeName" placeholder="请输入入库人" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="入库部门" prop="deptId">
                <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择入库部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="入库时间" prop="storeTime">
                <el-date-picker clearable
                  v-model="form.storeTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择入库时间"
                  :default-value="new Date()"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资产名称" prop="assetName">
                <el-input v-model="form.assetName" placeholder="请输入资产名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="使用人" prop="useId">
                <el-input
                  v-model="form.useName"
                  :placeholder="form.useName ? '' : '请选择使用人'"
                  readonly
                  @click="openUserSelector('use')"
                />
              </el-form-item>
            </el-col>
            <!-- 共同使用人 -->
            <el-col :span="24">
              <el-form-item label="共同使用人" prop="jointUserId">
                <el-input
                  v-model="form.jointUserName"
                  :placeholder="form.jointUserName ? '' : '请选择共同使用人'"
                  readonly
                  @click="openUserSelector('joint')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="使用部门" prop="useDeptId">
                <el-input v-model="form.useDeptName" placeholder="请先选择共同使用人" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入编号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="购买时间" prop="purchaseTime">
                <el-date-picker clearable
                  v-model="form.purchaseTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择购买时间"
                  :default-value="new Date()"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="金额" prop="amount">
                <el-input v-model="form.amount" placeholder="请输入金额" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="form.brand" placeholder="请输入品牌" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="序列号" prop="serialNumber">
                <el-input v-model="form.serialNumber" placeholder="请输入序列号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="借出状态" prop="isLend">
                <el-select v-model="form.isLend"  :empty-values="[null, undefined]" placeholder="请选择借出状态" style="width: 100%">
                  <el-option
                    v-for="item in asset_lend_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 使用人选择对话框 -->
    <UserSelector
      v-model:visible="userSelectVisible"
      :title="userSelectTitle"
      :selected-user-ids="currentSelectedUserIds"
      :selected-user-names="currentSelectedUserNames"
      :multiple="isJoint"
      @confirmWithIds="handleUserSelectWithIds"
      @cancel="handleUserSelectCancel"
    />

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :http-request="handleUploadRequest" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="AdmAssetStore" lang="ts">
import { listAdmAssetStore, getAdmAssetStore, delAdmAssetStore, addAdmAssetStore, updateAdmAssetStore, importAsset } from '@/api/general/administration/asset/store';
import { getUsersByIds } from '@/api/system/user/index'
import { AdmAssetStoreVO, AdmAssetStoreQuery, AdmAssetStoreForm } from '@/api/general/administration/asset/store/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import UserSelector from '@/components/UserSelector/index.vue';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admAssetStoreList = ref<AdmAssetStoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const admAssetStoreFormRef = ref<ElFormInstance>();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 用户信息
const userStore = useUserStore();

// 引入数据字典
const { asset_lend_status, approval_record_status } = toRefs<any>(proxy?.useDict('asset_lend_status', 'approval_record_status'));

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 使用人员选择相关
const userSelectVisible = ref(false);
const userSelectTitle = ref('');
const isJoint = ref(false); // 区分使用人/共同使用人
const currentSelectedUserIds = ref('');
const currentSelectedUserNames = ref('');
const currentActualStage = ref<any>(null);
const currentSelectStageIndex = ref(-1);
const useDeptDisplay = ref('');      // 使用人部门展示
// 临时存储共同使用人及其部门信息
const jointUsers = ref<any[]>([]);

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/info/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmAssetStoreForm = {
  id: undefined,
  storeId: userStore.userId,
  storeName: userStore.name,
  deptId: undefined,
  storeTime: formatLocalDate(),
  assetName: undefined,
  useId: undefined,
  useName: undefined,
  useDeptId: undefined,
  useDeptName: undefined,
  jointUserId: undefined,
  jointUserName: undefined,
  number: undefined,
  purchaseTime: undefined,
  amount: undefined,
  brand: undefined,
  serialNumber: undefined,
  remark: undefined,
  status: undefined,
  approverIdea: undefined,
  isLend: undefined,
}
const data = reactive<PageData<AdmAssetStoreForm, AdmAssetStoreQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: undefined,
    deptId: undefined,
    storeTime: undefined,
    assetName: undefined,
    useId: undefined,
    jointUserId: undefined,
    useDeptId: undefined,
    number: undefined,
    purchaseTime: undefined,
    amount: undefined,
    brand: undefined,
    serialNumber: undefined,
    status: undefined,
    approverIdea: undefined,
    isLend: undefined,
    params: {
    }
  },
  rules: {
    storeId: [
      { required: true, message: "入库人不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "部门id不能为空", trigger: "blur" }
    ],
    storeTime: [
      { required: true, message: "入库时间不能为空", trigger: "change" }
    ],
    assetName: [
      { required: true, message: "资产名称不能为空", trigger: "blur" }
    ],
    useId: [
      { required: false, message: "使用人不能为空", trigger: "blur" }
    ],
    jointUserId: [
      { required: false, message: "共同使用人", trigger: "blur" }
    ],
    useDeptId: [
      { required: false, message: "共同使用人的部门", trigger: "blur" }
    ],
    number: [
      { required: true, message: "编号不能为空", trigger: "blur" },
      { 
        validator: (rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("编号不能包含中文字符"));
          } else {
            callback();
          }
        }, 
        trigger: "blur"
      }
    ],
    purchaseTime: [
      { required: true, message: "购买时间不能为空", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (value && form.value.storeTime) {
            const purchaseTime = new Date(value);
            const storeTime = new Date(form.value.storeTime);
            if (purchaseTime > storeTime) {
              callback(new Error("购买时间必须小于入库时间"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ],
    amount: [
      { 
        required: true, 
        message: "金额必须为正数", 
        trigger: "blur" 
      },
      { 
        validator: (rule, value, callback) => {
          if (value === undefined || value === '') {
            callback();
          } else if (!/^\d+(\.\d+)?$/.test(value) || Number(value) <= 0) {
            callback(new Error("金额必须为正数"));
          } else {
            callback();
          }
        }, 
        trigger: "blur" 
      }
    ],
    brand: [
      { required: true, message: "请输入品牌", trigger: "blur" }
    ],
    serialNumber: [
      { required: true, message: "请输入序列号", trigger: "blur" },
      { 
        validator: (rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("序列号不能包含中文字符"));
          } else {
            callback();
          }
        }, 
        trigger: "blur"
      }
    ],
    isLend: [
      { required: true, message: "请选择借出状态", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资产入库登记列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmAssetStore(params);
    const rows = res.rows || [];
    console.log('rows:', rows);
    // 收集所有 jointUserId，去重
    const allIds = new Set<string>();
    rows.forEach(row => {
      if (row.jointUserId && row.jointUserId !== 'null') { // 字符串 "null" 过滤
        console.log('通过的id:', row.jointUserId);
        row.jointUserId.split(',')
          .map(id => id.trim())
          .filter(id => id && id !== 'null') // 去掉空字符串和 "null"
          .forEach(id => allIds.add(id));
      }
    });
    // 批量获取用户信息
    const idList = Array.from(allIds);
    console.log('idList:', idList);
    let userMap: Record<string, string> = {};
    if (idList.length > 0) {
      const userRes = await getUsersByIds(idList); // 批量接口
      console.log('userRes:', userRes);
      // 假设 userRes.data 是数组 [{ userId, userName }]
      userMap = userRes.data.reduce((acc, u) => {
        if (u && u.userId) acc[u.userId] = u.userName;
        return acc;
      }, {} as Record<string, string>);
    }
    console.log('userMap:', userMap);
    // 映射用户名
    rows.forEach(row => {
      if (row.jointUserId) {
        const ids = row.jointUserId.split(',').map(id => id.trim());
        row.jointUserName = ids.map(id => userMap[id] || '').filter(Boolean).join(',');
      }
    });
    admAssetStoreList.value = rows;
    console.log('rows:', admAssetStoreList.value);
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  admAssetStoreFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmAssetStoreVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加资产入库登记";
}

const handleUpdate = async (row?: AdmAssetStoreVO) => {
  if (row?.status !== 0) {
    ElMessage.error("只能对未审核的申请进行修改");
    return;
  }
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAdmAssetStore(_id);
  Object.assign(form.value, res.data);
  // 处理共同使用人名称（批量获取）
  if (res.data.jointUserId) {
    const useIds = res.data.jointUserId.split(',').map(id => id.trim()).filter(Boolean);
    if (useIds.length > 0) {
      try {
        // 假设你有批量获取用户接口 getUsersByIds
        const userRes = await getUsersByIds(useIds); 
        // userRes.data 格式: [{ userId, userName }]
        const userMap = userRes.data.reduce((acc, u) => {
          if (u && u.userId) acc[u.userId] = u.userName;
          return acc;
        }, {} as Record<string, string>);
        // 映射用户名
        form.value.jointUserName = useIds.map(id => userMap[id] || '').filter(Boolean).join(',');
      } catch (error) {
        console.error('获取用户信息失败:', error);
        form.value.jointUserName = form.value.jointUserName || '';
      }
    }
  }
  console.log('修改资产入库登记:', res);
  dialog.visible = true;
  dialog.title = "修改资产入库登记";
};


/** 提交按钮 */
const submitForm = () => {
  admAssetStoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmAssetStore(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAdmAssetStore(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmAssetStoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除资产入库登记编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmAssetStore(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

// 处理更多命令
const handleMoreCommand = (command: string) => {
  switch (command) {
    case 'download-template':
      handleImportTemplate();
      break;
    case 'import-data':
      upload.open = true; // 打开上传弹窗
      upload.title = '导入物品';
      break;
    case 'export-data':
      handleExport();
      break;
    default:
      break;
  }
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download(
    '/system/admAssetStore/downloadTemplate',
    {},
    `admAssetStore_${Date.now()}.xlsx`
  );
};

const handleUploadRequest = async (option: any) => {
  if (!option.file) return;
  try {
    upload.isUploading = true;
    const form = {
      deptId: userStore.deptId,
      storeId: userStore.userId
    }

    // 调用你的接口
    await importAsset(option.file, form);

    ElMessage.success('导入成功');
    getList(); // 刷新列表
    option.onSuccess?.({ msg: '导入成功' }, option.file);
  } catch (err: any) {
    ElMessage.error(err?.message || '导入失败');
    option.onError?.(err);
  } finally {
    upload.isUploading = false;
    uploadRef.value?.clearFiles();
    upload.open = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admAssetStore/export', {
    ...queryParams.value
  }, `admAssetStore_${new Date().getTime()}.xlsx`)
}

/**
 * 提交上传文件
 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/**
 * 文件上传成功处理
 */
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();

  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  // 重新获取列表
  getList();
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

// 打开选择框
const openUserSelector = (type: 'use' | 'joint') => {
  isJoint.value = type === 'joint';
  userSelectTitle.value = type === 'use' ? '选择使用人' : '选择共同使用人';
  currentSelectedUserIds.value = type === 'use' ? String(form.value.useId) : String(form.value.jointUserId);
  currentSelectedUserNames.value = type === 'use' ? form.value.useName : form.value.jointUserName;
  userSelectVisible.value = true;
  currentActualStage.value = null;
  currentSelectStageIndex.value = type === 'use' ? -100 : -101;
};

// 处理使用人或共同使用人选择确认
const handleUserSelectWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  if (isJoint.value) {
    // 创建一个 Map，存储现有 jointUsers 的部门信息
    const deptMap = new Map<string, { deptId: string; deptName: string }>();
    jointUsers.value.forEach(u => {
      deptMap.set(u.userId, { deptId: u.deptId, deptName: u.deptName });
    });

    // 遍历子组件返回的用户，保留原有部门信息，如果没有则用子组件提供的或默认
    jointUsers.value = data.users.map(u => {
      const existDept = deptMap.get(u.userId);
      return {
        userId: u.userId,
        userName: u.userName
      };
    });

    // 更新表单
    form.value.jointUserId = jointUsers.value.map(u => u.userId).join(',');
    form.value.jointUserName = jointUsers.value.map(u => u.userName).join(',');
  } else {
    const u = data.users[0];
    form.value.useId = u.userId;
    form.value.useName = u.userName;
    form.value.useDeptId = u.deptId || '';
    form.value.useDeptName = u.deptName || '';
  }

  handleUserSelectCancel();
};



// 取消选择
const handleUserSelectCancel = () => {
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
  userSelectVisible.value = false;
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>
